<template>
    <span @click="destroy" :loading="loading">
        <slot :disabled="!selected.length"></slot>
    </span>
</template>

<script>
    export default {
        name: "index",
        props: {
            route: {
                type: String,
                required: true,
            },
            primary: {
                type: String,
                default () {
                    return 'id';
                }
            },
            selected: {
                type: Array,
                required: true,
            },
        },
        data() {
            return {
                loading: false,
            };
        },
        methods: {
            destroy() {
                if (!this.selected.length) {
                    this.$message.warning('请选择要删除数据');
                    return;
                }
                // 防止有些页面直接传入 object
                let selected = this.selected.map(v => {
                    if (isNaN(v)) {
                        if (v.hasOwnProperty(this.primary) && !isNaN(v[this.primary])) {
                            return v[this.primary];
                        }
                        return 0;
                    }
                    return v;
                });
                this.$confirm('批量删除后将无法恢复, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.loading = true;
                    this.$store.dispatch(this.route, selected).then(res => {
                        this.$message.success('ID: ' + selected.join(',') + ' 删除成功');
                        this.$emit('success');
                    }).catch(err => {
                        // this.$message.error('ID: ' + primary + ' 删除失败');
                    }).finally(() => {
                        this.loading = false;
                    })
                });
            },
        }
    }
</script>

<style scoped>

</style>
